import React, { useState, useEffect } from 'react';
import { Layout, Typography, Card, Progress, Statistic, List, Calendar, Badge, Avatar, Button, Row, Col, Tabs, Tag } from 'antd';
import { UserOutlined, StarOutlined, FileTextOutlined, BellOutlined, CalendarOutlined, UserAddOutlined, CheckOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { userService } from '../services/userService';
import type { UserInfo } from '../services/userService';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';



import '../App.css';
// 设置中文语言
dayjs.locale('zh-cn');
const { Title, Text } = Typography;
const { Content } = Layout;
const { TabPane } = Tabs;

// 模拟数据
const mockJobApplications = [
    { id: 1, company: '科技有限公司', position: '前端工程师', status: '已投递', date: '2025-01-15', progress: 20 },
    { id: 2, company: '互联网创新公司', position: 'React开发', status: '面试中', date: '2025-01-10', progress: 50 },
    { id: 3, company: '数字科技集团', position: '全栈开发', status: '已录用', date: '2025-01-05', progress: 100 },
];

const mockRecommendedJobs = [
    { id: 1, title: '高级前端开发工程师', company: '科技创新公司', salary: '25K-35K', tags: ['React', 'TypeScript', '3年+'] },
    { id: 2, title: 'React全栈工程师', company: '互联网大厂', salary: '20K-30K', tags: ['React', 'Node.js', '5年+'] },
    { id: 3, title: '前端架构师', company: '金融科技公司', salary: '30K-50K', tags: ['架构设计', 'React', '8年+'] },
];

const mockMessages = [
    { id: 1, title: '面试邀请', content: '您已收到来自科技有限公司的面试邀请', time: '今天 10:30', unread: true },
    { id: 2, title: '简历通过筛选', content: '您的简历已通过互联网创新公司的初步筛选', time: '昨天 15:45', unread: true },
    { id: 3, title: '系统通知', content: '您的账号信息已更新成功', time: '2025-01-14', unread: false },
];

const mockCalendarEvents = [
    { title: '技术面试', date: '2025-01-20', type: '面试' },
    { title: 'HR面试', date: '2025-01-22', type: '面试' },
    { title: '入职体检', date: '2025-01-25', type: '体检' },
];

const Profile: React.FC = () => {
    const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
    const [profileCompletion, setProfileCompletion] = useState(65);
    const [missingItems, setMissingItems] = useState<string[]>(['教育经历', '工作经验', '技能证书', '项目经验']);
    const navigate = useNavigate();

    useEffect(() => {
        // 从localStorage获取用户信息
        const storedUserInfo = localStorage.getItem('userInfo');
        if (storedUserInfo) {
            setUserInfo(JSON.parse(storedUserInfo));
        }

        // 如果没有用户信息或token，重定向到登录页
        const token = localStorage.getItem('token');
        if (!token || !storedUserInfo) {
            navigate('/login');
        }
    }, [navigate]);

    const handleLogout = () => {
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        navigate('/login');
    };

    const getStatusColor = (status: string) => {
        switch (status) {
            case '已投递': return '#1890ff';
            case '面试中': return '#faad14';
            case '已录用': return '#52c41a';
            case '已拒绝': return '#f5222d';
            default: return '#d9d9d9';
        }
    };

    const getStatusIcon = (status: string) => {
        switch (status) {
            case '已投递': return <ClockCircleOutlined />;
            case '面试中': return <UserAddOutlined />;
            case '已录用': return <CheckOutlined />;
            default: return <ClockCircleOutlined />;
        }
    };

    const renderCalendarDate = (value: any) => {
        const dateString = value.format('YYYY-MM-DD');
        const events = mockCalendarEvents.filter(event => event.date === dateString);
        return (
            <ul style={{ listStyle: 'none', padding: 0, margin: 0 }}>
                {events.map((event, index) => (
                    <li key={index} style={{ marginBottom: 5 }}>
                        <Tag color={event.type === '面试' ? 'blue' : 'green'}>{event.title}</Tag>
                    </li>
                ))}
            </ul>
        );
    };

    return (
        <Layout className="app-layout">
            <Content style={{ padding: '0 50px', marginTop: 64 }}>
                <div className="site-layout-content">
                    <div style={{ marginBottom: 24 }}>
                        <Title level={2}>个人中心</Title>
                    </div>

                    <Row gutter={[16, 16]}>
                        {/* 用户基本信息卡片 */}
                        <Col xs={24} md={8}>
                            <Card className="profile-card">
                                <div style={{ textAlign: 'center' }}>
                                    <Avatar size={100} icon={<UserOutlined />} style={{ marginBottom: 16 }} />
                                    <Title level={4}>{userInfo?.fullName || '用户'}</Title>
                                    <Text type="secondary">{userInfo?.email}</Text>
                                    <Tag color={userInfo?.userType === 'jobseeker' ? 'blue' : 'green'} style={{ marginTop: 8 }}>
                                        {userInfo?.userType === 'jobseeker' ? '求职者' : '招聘方'}
                                    </Tag>
                                </div>

                                <div style={{ marginTop: 24 }}>
                                    <Button type="primary" block style={{ marginBottom: 8 }}>
                                        编辑个人资料
                                    </Button>
                                    <Button danger block onClick={handleLogout}>
                                        退出登录
                                    </Button>
                                </div>
                            </Card>
                        </Col>

                        {/* 资料完整度卡片 */}
                        <Col xs={24} md={16}>
                            <Card className="profile-card">
                                <Title level={5}>个人资料完整度</Title>
                                <Progress percent={profileCompletion} strokeColor="#1890ff" />
                                <Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
                                    完善资料可提高简历曝光率和匹配度
                                </Text>

                                {missingItems.length > 0 && (
                                    <div style={{ marginTop: 16 }}>
                                        <Text type="warning">待完善项目：</Text>
                                        <div style={{ marginTop: 8 }}>
                                            {missingItems.map((item, index) => (
                                                <Tag key={index} color="warning" style={{ marginRight: 8, marginBottom: 8 }}>
                                                    {item}
                                                    <Button type="text" size="small" style={{ color: '#fff', padding: 0 }}>
                                                        去完善
                                                    </Button>
                                                </Tag>
                                            ))}
                                        </div>
                                    </div>
                                )}
                            </Card>
                        </Col>
                    </Row>

                    <Tabs defaultActiveKey="1" style={{ marginTop: 16 }}>
                        {/* 投递进度看板 */}
                        <TabPane tab="投递进度" key="1">
                            <List
                                className="application-list"
                                itemLayout="vertical"
                                dataSource={mockJobApplications}
                                renderItem={(item) => (
                                    <List.Item
                                        key={item.id}
                                        actions={[
                                            <Progress percent={item.progress} size="small" strokeColor={getStatusColor(item.status)} />
                                        ]}
                                        extra={
                                            <Tag color={getStatusColor(item.status)} icon={getStatusIcon(item.status)}>
                                                {item.status}
                                            </Tag>
                                        }
                                    >
                                        <List.Item.Meta
                                            title={
                                                <div>
                                                    <Text strong>{item.company}</Text>
                                                    <Text style={{ marginLeft: 16 }}>{item.position}</Text>
                                                </div>
                                            }
                                            description={`投递时间：${item.date}`}
                                        />
                                    </List.Item>
                                )}
                            />
                        </TabPane>

                        {/* AI推荐职位 */}
                        <TabPane tab="AI推荐" key="2">
                            <List
                                className="recommended-jobs"
                                itemLayout="vertical"
                                dataSource={mockRecommendedJobs}
                                renderItem={(item) => (
                                    <List.Item
                                        key={item.id}
                                        actions={[
                                            <Button type="primary" icon={<StarOutlined />}>
                                                收藏
                                            </Button>,
                                            <Button icon={<FileTextOutlined />}>
                                                立即投递
                                            </Button>
                                        ]}
                                    >
                                        <List.Item.Meta
                                            title={
                                                <div>
                                                    <Text strong>{item.title}</Text>
                                                    <Text style={{ marginLeft: 16, color: '#f5222d' }}>{item.salary}</Text>
                                                </div>
                                            }
                                            description={item.company}
                                        />
                                        <div>
                                            {item.tags.map((tag, index) => (
                                                <Tag key={index} style={{ marginRight: 8, marginBottom: 8 }}>
                                                    {tag}
                                                </Tag>
                                            ))}
                                        </div>
                                    </List.Item>
                                )}
                            />
                        </TabPane>

                        {/* 面试日历 */}
                        <TabPane tab="面试日历" key="3">
                            <Card className="calendar-card">
                                // 修复Calendar组件的headerRender函数
                                <Calendar
                                  fullscreen={false}
                                  cellRender={renderCalendarDate}
                                  headerRender={(headerProps) => (
                                    <div style={{ textAlign: 'center', padding: 16 }}>
                                      <Title level={4}>{dayjs(headerProps.value).format('YYYY年MM月')}</Title>
                                    </div>
                                  )}
                                />
                            </Card>
                        </TabPane>

                        {/* 消息中心 */}
                        <TabPane tab="消息中心" key="4">
                            <List
                                className="message-list"
                                dataSource={mockMessages}
                                renderItem={(item) => (
                                    <List.Item
                                        key={item.id}
                                        extra={
                                            item.unread && (
                                                <Badge dot />
                                            )
                                        }
                                    >
                                        <List.Item.Meta
                                            title={
                                                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                                                    <Text strong>{item.title}</Text>
                                                    <Text type="secondary">{item.time}</Text>
                                                </div>
                                            }
                                            description={item.content}
                                        />
                                    </List.Item>
                                )}
                            />
                        </TabPane>
                    </Tabs>
                </div>
            </Content>
        </Layout>
    );
};

export default Profile;